package com.imooc.sm.global;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 对登录进行限制
 */
public class LoginFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        String path = request.getServletPath();

        if(path.toLowerCase().indexOf("login")!=-1){
            filterChain.doFilter(request,response);
        }else{
            HttpSession session = request.getSession();
            Object obj =session.getAttribute("USER");
            if(obj!=null){
                /*如果存在已有的登录账号则无需再次登录*/
                filterChain.doFilter(request,response);
            }else{
                /*跳转到对应页面，必须绝对路径，有二级目录和其他目录的toLogin都不可以*/
                response.sendRedirect(request.getContextPath()+"/toLogin.do");
            }
        }
    }

    public void destroy() {

    }
}
